package String;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class _890_FindandReplacePattern {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> res = new ArrayList<>();
        Map<Character, Character> maps = new HashMap<>();
        Map<Character, Character> maps2 = new HashMap<>();
        int len = pattern.length();
        for (String word : words) {
            if (len != word.length()) {
                continue;
            } else {
                boolean flag = false;
                for (int i = 0; i < len; i++) {
                    if (maps.containsKey(pattern.charAt(i))) {
                        if (maps.get(pattern.charAt(i)) != word.charAt(i)) {
                            flag = true;
                            break;
                        }
                    }
                    if (maps2.containsKey(word.charAt(i))) {
                        if (maps2.get(word.charAt(i)) != pattern.charAt(i)) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        maps.put(pattern.charAt(i), word.charAt(i));
                        maps2.put(word.charAt(i), pattern.charAt(i));
                    }
                }
                if (!flag) {
                    res.add(word);
                }
            }
            maps = new HashMap<>();
            maps2 = new HashMap<>();
        }
        return res;
    }
}
